package org.micode.demo.web.service;

import org.micode.common.domain.DataPage;
import org.micode.common.domain.Page;
import org.micode.common.domain.vo.EditObjVO;
import org.micode.common.domain.vo.KeyVO;
import org.micode.common.exception.DataException;
import org.micode.common.helper.I18nMsgHelper;
import org.micode.demo.db.domain.dto.SysRoleDTO;
import org.micode.demo.db.domain.query.SysRoleQuery;
import org.micode.demo.db.service.DaoSysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 角色信息(sys_role) 的APP服务实现类
 *
 * author: wutianbin
 */
@Service
@Slf4j
public class SysRoleService {

    private static final int MAX_ROLE_NUM = 10000;

    @Autowired
    private DaoSysRoleService daoSysRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    public DataPage<SysRoleDTO> list(SysRoleQuery dataQuery) {
        return daoSysRoleService.listPage(dataQuery);
    }

    public SysRoleDTO info(KeyVO<Long> roleId) {
        SysRoleDTO role = daoSysRoleService.get(roleId.getKey());
        if (null != role) {
            //查询角色对应的菜单
            List<Long> menuIdList = sysRoleMenuService.queryRoleMenuIdList(roleId.getKey());
            role.setMenuIdList(menuIdList);
        }
        return role;
    }

    public SysRoleDTO insert(SysRoleDTO sysRole) {
        return daoSysRoleService.insert(sysRole);
    }

    public Integer update(SysRoleDTO sysRole) {
        return daoSysRoleService.update(sysRole);
    }

    public Integer delete(EditObjVO<List<Long>> delIds) {
        // 默认用户不能删除，所以需要先排除默认用户
        List<Long> ids = daoSysRoleService.listNotDefault(delIds.getWantEdit());
        if (null == ids || ids.size() <= 0) {
            return 0;
        } else if (ids.size() < delIds.getWantEdit().size()) {
            // 选择的用户里面有系统规默认用户
            throw new DataException(I18nMsgHelper.get("valid.role.delete.have-default-role"));
        }

        return daoSysRoleService.deleteByKeys(delIds);
    }

    public List<SysRoleDTO> listAll() {
        SysRoleQuery query = new SysRoleQuery();
        Page page = Page.numberPage(MAX_ROLE_NUM);
        query.setPage(page);
        DataPage<SysRoleDTO> ret = list(query);
        if (null != ret && null != ret.getList()) {
            return ret.getList();
        }
        return null;
    }

}
